package course.controller;

import cn.hutool.crypto.digest.DigestUtil;
import course.pojo.entity.Student;
import course.service.StudentService;
import course.service.impl.StudentServiceImpl;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author HLF
 * @date 2022/7/5 16:00
 */
@WebServlet("/student/studentLoginController")
public class StudentLoginController extends BaseController {
    private StudentService studentService = new StudentServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String spassword = req.getParameter("spassword");

        if (!StringUtils.isNumeric(sid) || StringUtils.isBlank(spassword) || StringUtils.isBlank(sid)) {
            req.setAttribute("msg", "学号或密码不能为空或格式不正确！");
            req.getRequestDispatcher("/student_login.jsp").forward(req, resp);
        }

        Student student = studentService.getById(Integer.valueOf(sid));

        if (student == null) {
            req.setAttribute("msg", "学号或密码错误！");
            req.getRequestDispatcher("/student_login.jsp").forward(req, resp);
        } else {
            String pass = student.getSpassword();
            boolean check = DigestUtil.bcryptCheck(spassword, pass);
            if (!check) {
                req.setAttribute("msg", "学号或密码错误！");
                req.getRequestDispatcher("/student_login.jsp").forward(req, resp);
            } else {
                HttpSession session = req.getSession();
                session.setAttribute("sstudent", student);
                session.setAttribute("role", "student");
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            }
        }
    }

    /**
     * 学生退出登录
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("sstudent");
        req.getSession().removeAttribute("role");

        resp.sendRedirect(req.getContextPath() + "/index.jsp");

    }
}
